package com.sky.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sky.context.EmployeeContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    /**
     * 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        
        // 自动填充更新时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        // 自动填充创建人（从ThreadLocal获取）
        Long currentEmployeeId = EmployeeContext.getCurrentEmp();
        if (currentEmployeeId != null) {
            this.strictInsertFill(metaObject, "createUser", Long.class, currentEmployeeId);
            this.strictInsertFill(metaObject, "updateUser", Long.class, currentEmployeeId);
        }
    }
    
    /**
     * 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        // 自动填充更新人（从ThreadLocal获取）
        Long currentEmployeeId = EmployeeContext.getCurrentEmp();
        if (currentEmployeeId != null) {
            this.strictUpdateFill(metaObject, "updateUser", Long.class, currentEmployeeId);
        }
    }
}